#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <uv.h>

static void dns_resolved_cb(uv_getaddrinfo_t *req, int status, struct addrinfo *res) {
    if (status < 0) {
        fprintf(stderr, "Error resolving %s: %s\n", (char *)req->data, uv_strerror(status));
        return;
    }

    char addr[INET_ADDRSTRLEN+1];
    struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
    uv_ip4_name(ipv4, addr, INET_ADDRSTRLEN);
    fprintf(stdout, "Resolved to %s\n", addr);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <domain>\n", argv[0]);
        return 1;
    }

    const char *domain = argv[1];

    uv_loop_t *loop = uv_default_loop();
    uv_getaddrinfo_t resolver;
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;

    fprintf(stdout, "Resolving %s\n", domain);
    resolver.data = (void *)domain;
    uv_getaddrinfo(loop, &resolver, dns_resolved_cb, domain, NULL, &hints);

    int ret =uv_run(loop, UV_RUN_DEFAULT);
    uv_loop_close(loop);
    return ret;
}